using System.Reflection;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace 文件改名
{
    public partial class Form1 : Form
    {
        String parentPath; // 父目录
        String srcFileName; // 源文件名
        String dstFileName; // 目标文件名
        String suffix; // 后缀


        public Form1()
        {
            InitializeComponent();
        }


        private List<String> TraverseDirectory(string targetDirectory)
        {
            List<String> list = new List<String>();

            // 确保目标目录存在  
            if (!Directory.Exists(targetDirectory))
            {
                MessageBox.Show("目标目录不存在: " + targetDirectory, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return list;
            }

            try
            {
                // 获取目标目录中的文件和子目录  
                string[] fileEntries = Directory.GetFiles(targetDirectory);
                string[] subDirectoryEntries = Directory.GetDirectories(targetDirectory);

                // 遍历文件  
                foreach (string fileName in fileEntries)
                {
                    // 输出文件名（或根据需要执行其他操作）  

                    list.Add(Path.GetFileName(fileName).Trim());
                }

                // 递归遍历子目录  
                foreach (string subDirectory in subDirectoryEntries)
                {
                    // 调用自身来遍历子目录  
                    TraverseDirectory(subDirectory);
                }
            }
            catch (Exception ex)
            {
                // 处理异常（例如权限问题、路径不存在等）  
                MessageBox.Show("遍历目录时发生异常: " + ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            return list;
        }

        /// <summary>
        /// 选择文件夹
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SelectFolder(object sender, EventArgs e)
        {
            // 创建 FolderBrowserDialog 实例  
            using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog())
            {
                // 显示对话框  
                DialogResult result = folderBrowserDialog.ShowDialog();

                if (result == DialogResult.OK)
                {
                    // 用户选择了一个文件夹  
                    string selectedFolderPath = folderBrowserDialog.SelectedPath;

                    // 显示选中的文件夹
                    tbx_dir.Text = selectedFolderPath;

                    // 设置文件夹路径
                    parentPath = selectedFolderPath;
                    lb_dir.Text = selectedFolderPath;

                    List<string> list = TraverseDirectory(selectedFolderPath);
                    lbx_fileList.Items.Clear();
                    list.ForEach(fileName => lbx_fileList.Items.Add(fileName));
                }
            }
        }

        /// <summary>
        /// 获取选中的文件
        /// </summary>
        /// <returns></returns>
        private String GetSelectedFileName()
        {
            if (lbx_fileList.SelectedIndex != -1)
            {
                object selectedItem = lbx_fileList.SelectedItem;
                // 如果需要转换为特定类型（例如字符串），请进行转换  
                string selectedText = selectedItem as string;
                if (selectedText != null)
                {
                    return selectedText;
                }
            }
            return null;
        }

        /// <summary>
        /// 获取选中的方法
        /// </summary>
        /// <returns></returns>
        private String GetSelectdClassMethod(){
            if (cbb_method.SelectedIndex != -1)
            {
                object selectedItem = cbb_method.SelectedItem;
                // 如果需要转换为特定类型（例如字符串），请进行转换  
                string selectedText = selectedItem as string;
                if (selectedText != null)
                {
                    return selectedText;
                }
            }
            return null;
        }

        /// <summary>
        /// 选择文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lbx_fileList_SelectedValueChanged(object sender, EventArgs e)
        {
            if (lbx_fileList.SelectedIndex != -1)
            {
                object selectedItem = lbx_fileList.SelectedItem;
                // 如果需要转换为特定类型（例如字符串），请进行转换  
                string selectedText = selectedItem as string;
                if (selectedText != null)
                {
                    srcFileName = selectedText;
                    lb_src.Text = selectedText;

                    // 获取文件后缀，包括点号  
                    string extensionWithDot = Path.GetExtension(selectedText);
                    tbx_suffix.Text = extensionWithDot;
                    // 获取文件后缀，不包括点号  
                    string extensionWithoutDot = Path.GetExtension(selectedText).TrimStart('.');
                    suffix = extensionWithoutDot;
                    lb_suff.Text = extensionWithoutDot;

                    // 获取修改文件名的方法类
                    if (cbb_method.SelectedItem != null)
                    {
                        string selectedValue = cbb_method.SelectedItem.ToString();
                        // 定义全类名，包括命名空间  
                        string fullClassName = selectedValue; // 替换为你的命名空间  

                        // 获取类型信息  
                        Type type = Type.GetType(fullClassName);
                        if (type == null)
                        {
                            MessageBox.Show("Type not found.", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }

                        // 创建对象实例  
                        object instance = Activator.CreateInstance(type); // "Buddy" 是传递给构造函数的参数  
                        if (instance == null)
                        {
                            MessageBox.Show("Instance could not be created.", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            return;
                        }

                        // 调用无参方法  
                        MethodInfo barkMethod = type.GetMethod("Select");
                        if (barkMethod != null)
                        {
                            object? v = barkMethod.Invoke(instance, new String[] { selectedText }); // 调用方法，传递null作为参数列表（无参方法）  
                            List<String> lst = v as List<String>;
                            lbx_candidateNames.Items.Clear();
                            foreach (String name in lst)
                            {
                                lbx_candidateNames.Items.Add(name);
                            }
                        }
                        else
                        {
                            MessageBox.Show("Method not found.", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                        }
                    }
                    else
                    {
                        // 没有选中项或ComboBox为空  
                    }

                }
            }
        }
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {
            // 文件改名方法
            var implementingTypes = ReflectionHelper.GetAllTypesImplementingInterface<IFileSelecter>();
            foreach (var type in implementingTypes)
            {
                //Console.WriteLine(type.FullName);
                cbb_method.Items.Add(type.FullName);
            }
            cbb_method.SelectedIndex = 0;
            lbx_candidateNames.Items.Clear();
            lbx_fileList.Items.Clear();
        }

        /// <summary>
        /// 选择最终的文件名
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lbx_candidateNames_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lbx_candidateNames.SelectedIndex != -1)
            {
                object selectedItem = lbx_candidateNames.SelectedItem;
                // 如果需要转换为特定类型（例如字符串），请进行转换  
                string selectedText = selectedItem as string;
                if (selectedItem != null)
                {
                    tbx_finalName.Text = selectedText;
                    dstFileName = srcFileName;
                    lb_dist.Text = selectedText;
                }
            }
        }

        /// <summary>
        /// 文件改名方法列表选择
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cbb_method_SelectedIndexChanged(object sender, EventArgs e)
        {
            string fileName = GetSelectedFileName();
            if(fileName != null)
            {
                string fullClassName = GetSelectdClassMethod();
                if(fullClassName != null)
                {
                    // 获取类型信息  
                    Type type = Type.GetType(fullClassName);
                    if (type == null)
                    {
                        MessageBox.Show("Type not found.", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                    // 创建对象实例  
                    object instance = Activator.CreateInstance(type); // "Buddy" 是传递给构造函数的参数  
                    if (instance == null)
                    {
                        MessageBox.Show("Instance could not be created.", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                    // 调用无参方法  
                    MethodInfo barkMethod = type.GetMethod("Select");
                    if (barkMethod != null)
                    {
                        object? v = barkMethod.Invoke(instance, new String[] { fileName }); // 调用方法，传递null作为参数列表（无参方法）  
                        List<String> lst = v as List<String>;
                        lbx_candidateNames.Items.Clear();
                        foreach (String name in lst)
                        {
                            lbx_candidateNames.Items.Add(name);
                        }
                    }
                    else
                    {
                        MessageBox.Show("Method not found.", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }

                }
            }
        }
    }


    public interface IFileSelecter
    {
        List<String> Select(String fileName);
    }


    public class FileSelecter1 : IFileSelecter
    {
        public List<string> Select(string fileName)
        {
            fileName = fileName.Trim();
            string[] names = fileName.Split('-');
            return new List<string>(names);
        }
    }

    public class FileSelecter2 : IFileSelecter
    {
        public List<string> Select(string fileName)
        {
            return new List<string>{fileName};
        }
    }

    public class ReflectionHelper
    {
        public static List<Type> GetAllTypesImplementingInterface<T>()
        {
            var types = new List<Type>();
            // 获取当前执行程序集  
            var assembly = Assembly.GetExecutingAssembly();
            // 遍历程序集中的所有类型  
            foreach (var type in assembly.GetTypes())
            {
                // 检查类型是否实现了指定的接口  
                if (type.GetInterfaces().Contains(typeof(T)))
                {
                    types.Add(type);
                }
            }
            return types;
        }
    }
}
